package com.rw.tool.util.io;

import com.rw.tool.util.io.exception.StreamIOException;
import com.rw.tool.util.json.CastUtil;

import java.io.*;

/**
 * 序列化工具类
 */
public class SerializationUtil {
    /**
     * 把对象序列化为字符数组
     *
     * @param obj 对象
     * @return 序列化数组
     */
    public static byte[] toByte(Serializable obj) {
        try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
             ObjectOutputStream objectOut = new ObjectOutputStream(byteOut)) {
            objectOut.writeObject(obj);
            return byteOut.toByteArray();
        } catch (IOException e) {
            throw new StreamIOException(e);
        }
    }

    /**
     * 把字符数组反序列化为对象
     *
     * @param bytes 序列化后的字符数组
     * @return 对象
     */
    public static <T> T toObj(byte[] bytes) {
        try (ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
             ObjectInputStream objectIn = new ObjectInputStream(byteIn)) {
            return CastUtil.castObj(objectIn.readObject());
        } catch (IOException | ClassNotFoundException e) {
            throw new StreamIOException(e);
        }
    }
}
